package DAO.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import DAO.GenericDAO;
import DAO.HibernateUtil;


public  class GenericDAOImpl<T, ID> implements GenericDAO <T, ID> {
	
	public void save(T entity) {
		try {
			EntityManager hibernateSession = HibernateUtil.beginTransaction();
			hibernateSession.persist(entity);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
			e.printStackTrace();
            System.out.println("Error in save a new entity");
        } 	
	}

	public void merge(T entity) {
		try {
			EntityManager hibernateSession = HibernateUtil.beginTransaction();
			hibernateSession.merge(entity);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
			e.printStackTrace();
            System.out.println("Error in merge");
        } 	
	}

	public void delete(Object entity) {
		try {
			EntityManager hibernateSession = HibernateUtil.beginTransaction();
			hibernateSession.remove(entity);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
			e.printStackTrace();
            System.out.println("Error in delete entity");
        }
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll(Class<? extends Serializable> clazz) {
		List<T> t = null;
		try {
			EntityManager hibernateSession = HibernateUtil.beginTransaction();
			Query query = hibernateSession.createQuery("from " + clazz.getName());
			t =  (List<T>) query.getResultList();
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
			e.printStackTrace();
            System.out.println("Error in load all");
        }
	    return t;
	}

	@SuppressWarnings("unchecked")
	public List<T> findMany(Query query) {
        List<T> t = null;
        t = (List<T>) query.getResultList();
        return t;
    }

	@SuppressWarnings("unchecked")
	public T findOne(Query query) {
		T t = null;
	    t = (T) query.getSingleResult();
	    return t;
	}

	@SuppressWarnings("unchecked")
	public T findByID(Class<? extends Serializable> clazz, Integer id) {
		T t = null;
		try {
			EntityManager hibernateSession = HibernateUtil.beginTransaction();
			t = (T) hibernateSession.find(clazz, id);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
			e.printStackTrace();
            System.out.println("Error in find by ID");
        }
	    return t;
	}

}
